package com.child.java.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.child.java.pojo.UsersInfo;
import com.child.java.service.UsersInfoService;
import com.child.util.WebUtils;

@Controller
public class LoginController {
	
	@Autowired
	private UsersInfoService usersInfoService;
	
	@RequestMapping("/login")
	public String login(UsersInfo usersInfo,ModelMap map,HttpServletRequest request,HttpServletResponse response){
		
		UsersInfo user = usersInfoService.getByNameAndPwd(usersInfo.getUsername(), usersInfo.getPassword());
		if(user!=null){
			WebUtils.login(request, response, user, true);
			System.out.println("/login");
			return "redirect:/manager/showManager";
		}
		return "redirect:"+request.getContextPath()+"/login.jsp";
	}
	
	@RequestMapping("/regist")
	public String regist(@RequestParam("password2") String password2,@RequestParam("code") String code,UsersInfo usersInfo,ModelMap map,HttpSession session,HttpServletResponse response) throws IOException{
		System.out.println("CODE:"+session.getAttribute("CODE"));
		System.out.println("pass2:"+password2);
		System.out.println("code:"+code.toUpperCase());
		String vercode = (String) session.getAttribute("CODE");
		
		if(!vercode.toUpperCase().equals(code.toUpperCase())){
			map.put("message", "验证码错误！");
			return "/user/regist";
		}
		if(usersInfoService.getByName(usersInfo.getUsername())!=null){
			map.put("message", "用户名已被注册");
			return "/user/regist";
		}
		usersInfoService.insert(usersInfo);
		map.put("message", "注册成功!");
		return "/client/result";
	}
	
	@RequestMapping("/logout")
	public String logout(ModelMap map,HttpServletRequest request,HttpServletResponse response){
		WebUtils.logout(request, response);
		return "redirect:"+request.getContextPath()+"/login.jsp";
	}
	
	@RequestMapping("/tologin")
	public String toLogin(){
		System.out.println("tologin");
		return "/user/login";
	}
	
	@RequestMapping("/toregist")
	public String toRegist(){
		return "/user/regist";
	}

}
